<template>
  <el-card style="height: 100%;">
    <div>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="姓氏"
        v-model="searchList.firstName"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="名字"
        v-model="searchList.lastName"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="用户名"
        v-model="searchList.username"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="电话"
        v-model="searchList.phone"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="邮箱"
        v-model="searchList.email"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" :icon="Search" round @click="GetUserInfo(page, pageSize)">搜索</el-button>
      <el-button v-if="PERMISSION_BUTTON.CREATE" type="success" plain round @click="showData($event, false, false)">
        新增用户
      </el-button>
      <el-button v-if="PERMISSION_BUTTON.DELETE_LIST" @click="handleDelete(SelectionUserInfo)" type="danger" plain
                 round>批量删除
      </el-button>
    </div>
    <el-table :max-height="600" :data="UserInfoList" stripe style="font-size:15px"
              @row-dblclick="showData($event, true, false)"
              @selection-change="SelectionUserInfo = $event.map((item) => item.ID)">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="编号" width="100" type="index" align="center"/>
      <el-table-column prop="FIRST_NAME" label="姓氏"/>
      <el-table-column prop="LAST_NAME" label="名字"/>
      <el-table-column prop="USERNAME" label="用户名"/>
      <el-table-column prop="PHONE" label="联系电话"/>
      <el-table-column prop="EMAIL" label="邮箱" show-overflow-tooltip/>
      <el-table-column prop="DATE_JOINED" label="加入时间"
                       :formatter="(row) => row.DATE_JOINED == null ? '' : dayjs(row.DATE_JOINED).format('YYYY-MM-DD HH:mm:ss') "
                       show-overflow-tooltip/>
      <el-table-column prop="LAST_LOGIN" label="最后登录时间" show-overflow-tooltip
                       :formatter="(row) => row.LAST_LOGIN == null ? '' : dayjs(row.LAST_LOGIN).format('YYYY-MM-DD HH:mm:ss')"/>
      <el-table-column align="center" label="操作" min-width="150">
        <template #default="scope">
          <el-button v-if="PERMISSION_BUTTON.UPDATE" size="small" type="primary"
                     @click.stop="showData(scope.row, false,true)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click.stop="handleDelete(scope.row)"
            v-if="PERMISSION_BUTTON.DELETE"
          >
            删除
          </el-button>
          <el-dropdown v-if="PERMISSION_BUTTON.ASSIGN" placement="top-start" trigger="click" style="margin-left: 10px">
            <el-button size="small" type="success" @click.native="defaultCheckList(scope.row.USERNAME)">分配角色</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-checkbox-group v-model="roleCheckList" :min="1" :max="3" @change="handleAssign(scope.row.ID)">
                  <el-dropdown-item v-for="item in RoleInfoList">
                    <el-checkbox :label="item.ID" :key="item.ID">{{ item.NAME }}</el-checkbox>
                  </el-dropdown-item>
                </el-checkbox-group>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="(val) => pageSize = val"
      @current-change="(val) => page = val"
    />
    <el-dialog v-model="dialogFormVisible" width="500">
      <el-form :model="form">
        <el-form-item label="姓氏" :label-width="formLabelWidth">
          <el-input v-model="form.firstName" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="名字" :label-width="formLabelWidth">
          <el-input v-model="form.lastName" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item v-if="!isEdit && !dialogDisabled" label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.phone" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>

import { useStore } from 'vuex';
import { onBeforeMount, reactive, ref, toRefs, watch } from 'vue';
import { get, post } from '@/api/https';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { flatten, hasPermission } from '@/utils';
import { USER } from '@/utils/permission';

export default {
  name: 'UserView',
  setup() {
    const store = useStore();
    const data = reactive({
      UserInfoList: [],
      RoleInfoList: [],
      roleCheckList: [],
      SelectionUserInfo: [],
      total: 0,
      form: {
        id: '',
        firstName: '',
        lastName: '',
        username: '',
        password: '',
        phone: '',
        email: '',
        // DATE_JOINED: "",
        // LAST_LOGIN: ""
      },
      formLabelWidth: 80,
      searchList: {
        firstName: '',
        lastName: '',
        username: '',
        phone: '',
        email: ''
      },
      PERMISSION_BUTTON: {
        CREATE: false,
        UPDATE: false,
        DELETE: false,
        DELETE_LIST: false,
        ASSIGN: false
      }
    });

    const page = ref(1);
    const pageSize = ref(10);
    let dialogFormVisible = ref(false);
    let dialogDisabled = ref(false);
    let isEdit = ref(false);

    async function defaultCheckList(username) {
      const response = await get('/user/get-menu-by-username/', {
        'username': username,
        'isGetRole': true
      });
      if (response.code == 200) {
        data.roleCheckList = response.data;
      } else {
        ElMessage({
          message: '获取当前用户角色信息失败',
          type: 'warning'
        });
      }
    }

    async function GetUserInfo(page, pageSize) {
      let userinfo = await get('/user/get-list/', {
        ...data.searchList,
        'page': page,
        'pageSize': pageSize
      });
      data.UserInfoList = userinfo.data.data;
      data.total = parseInt(userinfo.data.total);
    }

    onBeforeMount(async () => {
      // await store.dispatch('getAccountData');
      await GetUserInfo(page.value, pageSize.value);
      // 获取所有角色信息
      const response = await get('/role/get-all/');
      if (response.code == 200) {
        data.RoleInfoList = response.data;
      } else {
        ElMessage({
          message: '获取角色信息失败',
          type: 'warning'
        });
      }
      data.PERMISSION_BUTTON.CREATE = await hasPermission(USER.SYSTEM_USER_CREATE);
      data.PERMISSION_BUTTON.UPDATE = await hasPermission(USER.SYSTEM_USER_UPDATE);
      data.PERMISSION_BUTTON.DELETE = await hasPermission(USER.SYSTEM_USER_DELETE);
      data.PERMISSION_BUTTON.DELETE_LIST = await hasPermission(USER.SYSTEM_USER_DELETE_LIST);
      data.PERMISSION_BUTTON.ASSIGN = await hasPermission(USER.SYSTEM_USER_ASSIGN);
    });

    //监听当前页变化
    watch(page, async () => {
      await GetUserInfo(page.value, pageSize.value);
    });

    //监听每页个数变化
    watch(pageSize, async () => {
      page.value = 1;
      await GetUserInfo(page.value, pageSize.value);
    });

    function handleEdit() {
      if (dialogDisabled.value) {
        return;
      }
      ElMessageBox.confirm(`是否确认${isEdit.value ? '修改' : '添加'}当前用户信息`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
        // center: true,
        // roundButton: true,
      })
        .then(async () => {
          const response = await post(`${isEdit.value ? '/user/update/' : '/user/create/'}`, data.form);
          if (response.code == 200) {
            dialogFormVisible.value = false;
            await GetUserInfo(page.value, pageSize.value);
            ElMessage({
              message: `${isEdit.value ? '修改' : '添加'}用户成功`,
              type: 'success',
            });
          } else {
            dialogFormVisible.value = false;
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    function handleDelete(row) {
      ElMessageBox.confirm('确定删除当前记录？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
      })
        .then(async () => {
          let deleteIdList = [];
          if (row instanceof Array) {
            deleteIdList.push(...row);
          } else if (row instanceof Object) {
            deleteIdList.push(row.ID);
          }
          if (deleteIdList.length == 0) {
            ElMessage({
              message: `请选择需要删除的信息`,
              type: 'warning',
            });
            return;
          }
          const response = await post('/user/delete-list/', deleteIdList);
          if (response.code == 200) {
            await GetUserInfo(page.value, pageSize.value);
            ElMessage({
              message: `成功删除 ${response.data.count} 条记录`,
              type: 'success',
            });
          } else {
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    function handleAssign(userId) {
      ElMessageBox.confirm('确认为当前用户分配角色', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
      })
        .then(async () => {
          const response = await post('/user/assigning-roles/', {
            'userId': userId,
            'roleIdList': data.roleCheckList
          });
          if (response.code == 200) {
            ElMessage({
              message: `用户角色分配成功`,
              type: 'success',
            });
            // 重新获取当前角色权限
            const {
              code,
              data
            } = await get('/user/get-menu-by-username/', {
              username: localStorage.getItem('user'),
              isGetRole: false
            });
            if (code == 200) {
              store.state.Permissions = flatten(data)
                .filter(item => item.MENU_TYPE == 3)
                .map(item => item.PERMS);
            } else {
              ElMessage({
                type: 'error',
                message: data.message
              });
            }
          } else {
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    function showData(row, disabled, edit) {
      dialogFormVisible.value = true;
      dialogDisabled.value = disabled;
      isEdit.value = edit;
      if (!isEdit.value && !dialogDisabled.value) {
        data.form.id = '';
        data.form.firstName = '';
        data.form.lastName = '';
        data.form.username = '';
        data.form.password = '';
        data.form.phone = '';
        data.form.email = '';
      } else {
        data.form.id = row.ID;
        data.form.firstName = row.FIRST_NAME;
        data.form.lastName = row.LAST_NAME;
        data.form.username = row.USERNAME;
        data.form.password = row.PASSWORD;
        data.form.phone = row.PHONE;
        data.form.email = row.EMAIL;
      }
    }

    return {
      ...toRefs(data),
      page,
      pageSize,
      dialogFormVisible,
      dialogDisabled,
      isEdit,
      handleEdit,
      handleDelete,
      handleAssign,
      showData,
      dayjs,
      defaultCheckList,
      GetUserInfo,
      Search
    };
  },
};
</script>

<style scoped>
.el-input {
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 5px;
  margin-bottom: 10px;
}
</style>
